package com.cloudlegal.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * MyBatis Plus配置
 * 
 * @author CloudLegal Team
 * @since 2024-01-01
 */
@Configuration
public class MybatisPlusConfig {

    /**
     * MyBatis Plus拦截器
     */
//    @Bean
//    public MybatisPlusInterceptor mybatisPlusInterceptor() {
//        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//
//        // 分页插件
//        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
//
//        return interceptor;
//    }

    /**
     * 元数据处理器
     */
    @Component
    public static class MyMetaObjectHandler implements MetaObjectHandler {

        @Override
        public void insertFill(MetaObject metaObject) {
            // 创建时间
            this.strictInsertFill(metaObject, "createdTime", LocalDateTime.class, LocalDateTime.now());
            // 更新时间
            this.strictInsertFill(metaObject, "updatedTime", LocalDateTime.class, LocalDateTime.now());
            
            // TODO: 从当前登录用户获取用户ID
            Long currentUserId = getCurrentUserId();
            if (currentUserId != null) {
                // 创建人
                this.strictInsertFill(metaObject, "createdBy", Long.class, currentUserId);
                // 更新人
                this.strictInsertFill(metaObject, "updatedBy", Long.class, currentUserId);
            }
        }

        @Override
        public void updateFill(MetaObject metaObject) {
            // 更新时间
            this.strictUpdateFill(metaObject, "updatedTime", LocalDateTime.class, LocalDateTime.now());
            
            // TODO: 从当前登录用户获取用户ID
            Long currentUserId = getCurrentUserId();
            if (currentUserId != null) {
                // 更新人
                this.strictUpdateFill(metaObject, "updatedBy", Long.class, currentUserId);
            }
        }

        /**
         * 获取当前登录用户ID
         * TODO: 实现从Security Context或其他方式获取当前用户ID
         */
        private Long getCurrentUserId() {
            // 这里应该从Spring Security Context或其他地方获取当前登录用户ID
            // 暂时返回null，后续实现JWT认证后再完善
            return null;
        }
    }
}
